/** 实例化im文件 */
import TIM from "./tim-wx.js";
import COS from "../imLibs/cos-wx-sdk-v5.js";
// import { genTestUserSig } from "../imLibs/debug/GenerateTestUserSig.js";
import api from "../../common/api.js";
import util from "../util.js";

const log = !util.isReleaseUrl ? console.log : () => {};
let _this;
export default class TimController {
  constructor(eventBus) {
    this.init();
    this.eventBus = eventBus;
    _this = this;
  }

  init() {
    let options = {
      // SDKAppID: 1400456086, // 接入时需要将0替换为您的即时通信 IM 应用的 SDKAppID
      SDKAppID: 1400500848, // 新账号
    };
    // 创建 SDK 实例，TIM.create() 方法对于同一个 SDKAppID 只会返回同一份实例
    let tim = TIM.create(options); // SDK 实例通常用 tim 表示

    // 设置 SDK 日志输出级别，详细分级请参见 setLogLevel 接口的说明
    if (util.isReleaseUrl) {
      tim.setLogLevel(1); // release 级别，SDK 输出关键信息，生产环境时建议使用
    } else {
      tim.setLogLevel(0); // 普通级别，日志量较多，接入时建议使用
    }

    // 注册 COS SDK 插件
    tim.registerPlugin({ "cos-wx-sdk": COS });
    // log({ tim });

    this.tim = tim;

    this.addEvent();

    // 将tim的所有方法拷贝过来
    for (const key in tim) {
      if (!this[key]) {
        this.constructor.prototype[key] = (...args) => {
          return tim[key](...args);
        };
      }
    }
  }

  // 此为判断当前是否已经im登录中的折中方式
  get sdkReady() {
    const ready = !!this.tim.getMyProfile();
    log("%c 获取 sdk状态！ ==>", "color: green", ready);
    return ready;
  }

  sdkReadyAndNext(id) {
    if (this.sdkReady) return Promise.resolve();

    return new Promise((resolve, reject) => {
      wx.showLoading({ title: "会话链接中..." });
      this.login(id).then(() => {
        setTimeout(() => {
          wx.hideLoading();
          wx.showToast({ icon: "success", title: "连接成功！" });
          resolve();
        }, 1000);
      });
    });
  }

  login(unionid) {
    return this._getSig(unionid).then((userSig) => {
      return this._timLogin(unionid, userSig);
    });
  }

  // 登录
  _timLogin(userID, userSig) {
    return this.tim
      .login({ userID, userSig })
      .then((imResponse) => {
        log("%c 登录成功", "color: green", imResponse.data);

        // 标识账号已登录，本次登录操作为重复登录。v2.5.1 起支持
        // if (imResponse.data.repeatLogin === true) {
        //   this.tim.logout().then(() => {
        //     this._timLogin(userID, userSig, true);
        //   });
        // }
      })
      .catch((imError) => {
        console.warn("login error:", imError); // 登录失败的相关信息
        return Promise.reject();
      });
  }

  _getSig(unionid) {
    return new Promise((resolve, reject) => {
      api.getUserSig(null, ({ data }) => {
        let userSig = data.content;
        resolve(userSig);
      });
      // let { userSig } = genTestUserSig(unionid);
      // resolve(userSig);
    });
  }

  // 登出
  loginOut() {
    let p = this.tim.logout();
    if (!p) return Promise.resolve();
    return p
      .then(({ data }) => {
        log("%c 登出 成功", "color: green", data);
        resolve();
      })
      .catch(({ data }) => {
        log("%c 登出 失败", "color: green", data);
        reject();
      });
  }

  createTextMessage(id, msg) {
    return this.tim.createTextMessage({
      to: id,
      conversationType: TIM.TYPES.CONV_C2C,
      payload: { text: msg },
    });
  }

  // 创建自定义消息
  createCustomMessage(id, payload) {
    return this.tim.createCustomMessage({
      to: id,
      conversationType: TIM.TYPES.CONV_C2C,
      payload: {
        data: "", //类型
        description: "", //请求or回应
        extension: "", //同意or拒绝
        ...payload,
      },
    });
  }

  createAudioMessage(id, file) {
    return this.tim.createAudioMessage({
      to: id,
      conversationType: TIM.TYPES.CONV_C2C,
      payload: { file },
    });
  }

  createImageMessage(id, file) {
    return this.tim.createImageMessage({
      to: id,
      conversationType: TIM.TYPES.CONV_C2C,
      payload: { file },
    });
  }

  // 设置消息已读
  setMessageRead(conversationID) {
    this.tim
      .setMessageRead({ conversationID })
      .then((e) => {
        log("%c 已读上报成功tim.setMessageRead", "color: green", e);
      })
      .catch((e) => {
        console.warn("已读上报失败tim.setMessageRead", e);
      });
  }

  // 获取用户资料
  getUserProfile(userIDList) {
    return this.tim
      .getUserProfile({
        userIDList, // 请注意：即使只拉取一个用户的资料，也需要用数组类型，例如：userIDList: ['user1']
      })
      .then(({ data }) => {
        log("%c 获取用户资料getUserProfile", "color: green", data);
        data.forEach((item) => {
          if (Array.isArray(item.profileCustomField)) {
            item.profileCustomField = item.profileCustomField.reduce((res, v) => {
              res[v.key] = v.value;
              return res;
            }, {});
          }
        });

        return Promise.resolve(data);
      })
      .catch((imError) => {
        console.warn("getUserProfile error:", imError); // 获取其他用户资料失败的相关信息
        return Promise.reject();
      });
  }

  addEvent() {
    this.tim.on(TIM.EVENT.CONVERSATION_LIST_UPDATED, this.onListUpdated);
    this.tim.on(TIM.EVENT.SDK_READY, this.onSdkReady);
    this.tim.on(TIM.EVENT.SDK_NOT_READY, this.onSdkNotReady);
    this.tim.on(TIM.EVENT.NET_STATE_CHANGE, this.onNetStateChange);
    this.tim.on(TIM.EVENT.MESSAGE_RECEIVED, this.onMessageReceived);
  }

  removeEvent() {
    this.tim.off(TIM.EVENT.CONVERSATION_LIST_UPDATED, this.onListUpdated);
    this.tim.off(TIM.EVENT.SDK_READY, this.onSdkReady);
    this.tim.off(TIM.EVENT.SDK_NOT_READY, this.onSdkNotReady);
    this.tim.off(TIM.EVENT.NET_STATE_CHANGE, this.onNetStateChange);
    this.tim.off(TIM.EVENT.MESSAGE_RECEIVED, this.onMessageReceived);
  }

  onListUpdated(e) {
    log("%c 监听到会话列表更新", "color: green", e.data);
    _this.eventBus.trigger(TIM.EVENT.CONVERSATION_LIST_UPDATED, e);
  }
  onSdkReady() {
    log("%c TIM.EVENT.SDK_READY sdk准备完毕！ ==>", "color: green");
    _this.eventBus.trigger(TIM.EVENT.SDK_READY);
  }
  onSdkNotReady() {
    log("%c TIM.EVENT.SDK_READY sdk掉线！ ==>", "color: green");
    _this.eventBus.trigger(TIM.EVENT.SDK_NOT_READY);
  }

  onMessageReceived(e) {
    log("%c TIM.EVENT.MESSAGE_RECEIVED 新消息", "color: green", e.data);
    _this.eventBus.trigger(TIM.EVENT.MESSAGE_RECEIVED, e);
  }

  onNetStateChange(e) {
    log("%c TIM.EVENT.onNetStateChange 网络变化！ ==>", "color: green", e);
    switch (e.data.state) {
      case TIM.TYPES.NET_STATE_CONNECTED: //已接入网络
        break;
      case TIM.TYPES.NET_STATE_CONNECTING: //连接中
        break;
      case TIM.TYPES.NET_STATE_DISCONNECTED: //未接入网络
        break;
    }
    _this.eventBus.trigger(TIM.EVENT.NET_STATE_CHANGE);
  }
}
